package com.biubiushop.socket.nio;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * @author chenjia
 * @date 2019/8/13
 **/
public class AcceptHandlerThread implements Runnable {

    ServerSocketChannel serverSocketChannel = null;
    Selector selector = null;
    Map<String, Object> map = null;


    public AcceptHandlerThread(ServerSocketChannel serverSocketChannel, Selector selector,
                               Map<String, Object> map) {
        this.serverSocketChannel = serverSocketChannel;
        this.selector = selector;
        this.map = map;
    }

    private static final Log log = LogFactory.get();

    private static final String CODING_TYPE = "gbk";

    @Override
    public void run() {
        try {
            log.info("接入连接");
            //如果是接入事件,创建socketChannel
            SocketChannel socketChannel = serverSocketChannel.accept();

            //设置为非阻塞模式
            socketChannel.configureBlocking(false);

            //将channel注册到selector,监听可读事件
            socketChannel.register(selector, SelectionKey.OP_READ);

            //将设备id与socketChannel作为键值对存入Map
            ByteBuffer byteBuffer = ByteBuffer.allocate(100);
            String id = null;
            if (socketChannel.read(byteBuffer) > 0) {
                //切换buffer为读模式
                byteBuffer.flip();
                id += Charset.forName(CODING_TYPE).decode(byteBuffer);
                map.put(id, socketChannel);
            }
            //回复客户端
            socketChannel.write(Charset.forName(CODING_TYPE).encode("Hello," + id + ",WELCOME TO SERVER!"));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
